package com.bhs.sansong.ui.message;


import static com.bhs.sansong.ui.shipments.CompleteAddressActivity.RC_LOCATION;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.PictureSelectAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.bean.CircleRefresh;
import com.bhs.sansong.bean.PictureBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.dialog.MyClickListener2;
import com.bhs.sansong.ui.other.LocationSelectionActivity;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.google.gson.Gson;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 发布圈子
 */
public class IssueCircleFriendsActivity extends BaseActivity implements NetCallBack, View.OnClickListener {

    private EditText mEtContent;
    private RecyclerView mRvPicture;
    private PictureSelectAdapter selectAdapter;
    private TextView mTvLocation;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private TextView mTvAnnouncementWordCount;
    private Button mTvIssue;
    private int isCompliance;//资源状态 0初始  1资源合规 2资源不合规  3资源还没查询完
    private String resource_type;

    @Override
    public int initLayout() {
        return R.layout.activity_issue_circle_friends;
    }

    @Override
    public void initView() {
        mEtContent = findViewById(R.id.et_content);
        mRvPicture = findViewById(R.id.rv_picture);
        mTvLocation = findViewById(R.id.tv_location);
        findViewById(R.id.ll_location).setOnClickListener(this);
        mEtContent.setFilters(MyUtils.inputFilters(this, 500));
        mTvAnnouncementWordCount = findViewById(R.id.tv_announcement_word_count);
        mTvIssue = findViewById(R.id.tv_issue);
        mTvIssue.setOnClickListener(this);
    }

    @Override
    public void initData() {
        selectAdapter = new PictureSelectAdapter(9, this);
        ArrayList<LocalMedia> localMedia = getIntent().getParcelableArrayListExtra("data");
        mRvPicture.setAdapter(selectAdapter);
        selectAdapter.setSelectMimeType(SelectMimeType.TYPE_ALL);
        mRvPicture.setLayoutManager(new GridLayoutManager(mContext, 3));
        selectAdapter.uploadPictures(localMedia);
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    mTvLocation.setText(result.getData().getStringExtra("name"));
                }
            }
        });

        mEtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvAnnouncementWordCount.setText(String.format("%s/500", s.length()));
                verify();
            }
        });

        selectAdapter.setMyClickListener(new MyClickListener2() {
            @Override
            public void onClick(String id, String info) {
                verify();
                //上传完检测 id=1上传完视频 删除不查
                if (id.equals("1")) {
                    //判断是否有不合规资源
                    for (int i = 0; i < selectAdapter.getData().size(); i++) {
                        if (selectAdapter.getData().get(i).getItemType() == PictureBean.picture &&
                                selectAdapter.getData().get(i).getIsCompliance() == 0) {
                            if (TextUtils.isEmpty(selectAdapter.getData().get(i).getVideoThumbnailPath())) {
                                networkRequest(netApi.baiduCheck(1, selectAdapter.getData().get(i).getNetworkPath()), IssueCircleFriendsActivity.this, i);
                                resource_type = "0";
                            } else {
                                resource_type = "1";
                                if (!TextUtils.isEmpty(selectAdapter.getData().get(i).getNetworkPath())) {
                                    networkRequest(netApi.baiduCheck(2, selectAdapter.getData().get(i).getNetworkPath()), IssueCircleFriendsActivity.this, i);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    private void verify() {
        boolean verify = !TextUtils.isEmpty(mEtContent.getText());
        if (TextUtils.isEmpty(selectAdapter.CommaSplice())) {
            verify = false;
        }
        mTvIssue.setEnabled(verify);
        mTvIssue.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.ll_location) {
            methodRequiresTwoPermission();
        } else if (view.getId() == R.id.tv_issue) {
            if (resource_type.equals("0")) {
                issue();
            } else {
                loadingPopupShow();
                isCompliance = 3;
                selectAdapter.uploadVideo();
            }
        }
    }

    private void issue() {
        isCompliance = 1;
        for (PictureBean datum : selectAdapter.getData()) {
            if (datum.getItemType() == PictureBean.picture) {
                if (datum.getIsCompliance() == 2) {
                    isCompliance = 2;
                    break;
                } else if (datum.getIsCompliance() == 0) {
                    isCompliance = 3;
                    break;
                }
            }
        }
        if (isCompliance == 2) {
            loadingPopupDismiss();
            ToastUtil.show("文件资源不合规，请调整后上传");
            return;
        }
        loadingPopupShow();
        if (isCompliance == 3) {
            return;
        }
        Map<String, String> map = new ArrayMap<>();
        map.put("role", "0");
        map.put("resource_type", resource_type);//资源类型，0：图片，1：视频
        map.put("words", mEtContent.getText().toString());
        map.put("resource", selectAdapter.CommaSplice());//资源
        map.put("location", mTvLocation.getText().toString());//资源
        if (resource_type.equals("1")) {
            if (!TextUtils.isEmpty(selectAdapter.getCover())) {
                map.put("cover", selectAdapter.getCover());
            }
        }
        networkRequest(netApi.publishCircle(map), this, 555);
    }

    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            goPage();
        } else {
            EasyPermissions.requestPermissions(this, "我需要您的位置信息", RC_LOCATION, perms);
        }
    }

    public void goPage() {
        Intent intent = new Intent(this, LocationSelectionActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 555) {
            loadingPopupDismiss();
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.getCode().equals("1")) {
                ToastUtil.show("发布成功");
                EventBus.getDefault().post(new CircleRefresh());
                finish();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        } else {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.getCode().equals("1")) {
                selectAdapter.getData().get(requestCode).setIsCompliance(1);
            } else {
                selectAdapter.getData().get(requestCode).setIsCompliance(2);
            }
            if ((isCompliance == 3)) {
                issue();
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


}